import path from "path";

const getAllChildren = (allRoutes) => {
  const result = []
  for (let i = 0; i < allRoutes.length; i++) {
    if (allRoutes[i].children && allRoutes[i].children.length) {
      result.push(...allRoutes[i].children.map(item => ({
        ...item,
        component: null,
        path: path.resolve(allRoutes[i].path, item.path)
      })))
    }
  }
  return result
}
const checkChildren = (children) => {
  if (!children || JSON.stringify(children) === '[]') return true

}
const checkMeta = (meta) => {
  if (!meta || JSON.stringify(meta) === "{}") return true
}
export const diffRoutes = (routes) => {
  const children = getAllChildren(routes)
  const result = []
  for (let i = 0; i < routes.length; i++) {
    if (!children.find(item => path.resolve(item.path) === path.resolve(routes[i].path))) {
      result.push(routes[i])
    }
  }
  return result.map(item => {
    const {path, meta, children,name} = item
    return {
      path,
      meta,
      children,
      name
    }
  })
}
export const generateRoutes = (routes, basePath = '/') => {
  const result = []
  for (let i = 0; i < routes.length; i++) {
    const currentRoute = routes[i]
    if (checkChildren(currentRoute.children) && checkMeta(currentRoute.meta)) continue
    if (checkMeta(currentRoute.meta) && !checkChildren(currentRoute.children)) {
      result.push(...generateRoutes(currentRoute.children, currentRoute.path))
      continue
    }
    const curPath = path.resolve(basePath, currentRoute.path);
    let flag = result.find(item => item.path === curPath)
    if (!flag) {
      flag = {
        ...currentRoute,
        path: curPath,
        children: [],
        component: null,
      }
      if (flag.meta.icon && flag.meta.title) {
        result.push(flag)
      }
    }
    if (!checkChildren(currentRoute.children)) {
      flag.children.push(...generateRoutes(currentRoute.children, curPath))
    }
  }
  return result;
}